<?php
/*************************************************

用户公共控制器 - the 
Author: WangHuabin <17-10-31>

*************************************************/
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller { 

    public function index(){
    }

    //图形验证码
    public function img_verify(){
        $sendVerifyName= I('get.verifyName');
        $sendVerifyName = md5($sendVerifyName . '12345');
        $v_config = verify();
        $Verify =     new \Think\Verify($v_config);
        $Verify->codeSet = '0123456789';
        $Verify->entry();
        $key = substr(md5($Verify->seKey), 5, 8);
        $str = substr(md5($Verify->seKey), 8, 10);
        $key = md5($key . $str);
        S($sendVerifyName, session($key), 180);
        // S($sendVerifyName,null);
    //    print_r(S($sendVerifyName));


    }
    //对比验证码
    function check_verify($code=0000,$verifyName=123,$id = ''){
        $verifyName = I('post.verifyName');
        $sendVerifyName = md5($verifyName.'12345');
       // echo $sendVerifyName;
        $Verifyarr = S($sendVerifyName);
        $Verify =     new \Think\Verify(); 
        $key = substr(md5($Verify->seKey), 5, 8);
        $str = substr(md5($code), 8, 10);
        $key = md5($key . $str);

    //    print_r($Verifyarr);
    //    print_r($key);
        // 验证码不能为空
        if(empty($code)){
            return false;
        }
        // session 过期
        if(NOW_TIME - $Verifyarr['verify_time'] > $Verify->expire) {
            S($sendVerifyName,null);
            return false;
        }

        if($key == $Verifyarr['verify_code']) {
            S($sendVerifyName,null);
            return true;
        }else{
            S($sendVerifyName,null);
            return false;
        }

    }

    //验证手机号码
    public function checkphone($val=0){
        $phone = I('post.phone');
        $map['user_phone'] = $phone;
        $r = D('User')->get_one($map);
        if($r){
            $data = array('errorCode'=>1,'msg'=>"手机号码已经注册！");
        }else{
            $data = array('errorCode'=>0,'msg'=>"手机号码未注册！");
        }
        if($val){
            return $data;
        }else{
            $this->ajaxReturn($data);
        }
    }



    //注册密码设置
    public function check_register(){
       // echo  $_SESSION['code_id'];die;
            $phone = I('post.phone');
            $code_id = I('post.code_id');
            $is_reg = $this->checkphone(1);
            $is_reg = json_decode($is_reg,true);
          
            if($is_reg['errorCode']==1){
                 $data = array('errorCode'=>7,'msg'=>"手机号码已经注册！");
                 $this->ajaxReturn($data);
            }
          //print_r($is_reg);
            $code = I('post.code');
            $password = I('post.password');
            $map['phone'] = $phone;
            $map['status'] = 0;
            $map['role'] = 1;
            $codeinfo = D('Verification')->get_one($map);
            // echo D('Verification')->_sql();
            // print_r($codeinfo);die;
                 if($codeinfo){
                    if($codeinfo['code']==$code && $codeinfo['status']==0){
                        if($codeinfo['time_failure']<=time()){
                            $data = array('errorCode'=>2,'msg'=>'验证码已过期！');
                            $this->ajaxReturn($data);
                        }else{
                            $data = array('errorCode'=>0);
                        }
                    }else{
                        $data = array('errorCode'=>3,'msg'=>'验证码错误！');
                        $this->ajaxReturn($data);
                    }
                }else{
                        $data = array('errorCode'=>4,'msg'=>'验证码无效！1');
                        $this->ajaxReturn($data);
                }
            
           
            

            $postdata['user_phone'] = $phone;
            $postdata['user_pass']  = I('post.password');
            $postdata['user_mixs']  = rand(111111,999999);
            $postdata['user_pass']  = md5($password.$postdata['user_mixs']);
            $postdata['user_name']  =rand(111,999).time();
            $postdata['nickname']   ="8号街".rand(1111,9999);
            $postdata['url_img']    =C('DOMAIN')."/App/Home/Public/images/default_photo.jpg";

             D('User')->startTrans();
            $res = D("User")->add($postdata);
            if($res){
                //用户信息拓展表
                $ip = get_client_ip_user();
                            $info_m = array(
                                'id_user'      => $res,
                                'form'         => 1,
                                'invite_code'  => '',
                                'joint_type'   => 0,
                                'joint_id'     => '',
                                'joint_token'  => '',
                                'joint_val'    => '',
                                'randpass'     => 0,
                                'verify_phone' => 1,
                                'verify_email' => 0,
                                'time_last'    => time(),
                                'time_add'     => time(),
                                'status'       => 0,
                                'ip'           => ip2long($ip),
                            );
                $uid['u_id'] = 812345+$res;
                $map = array();
                $map['id'] = $res;
                D("User")->edit($map,$uid);
                $r = D("UserInfo")->add($info_m);

                if($r){
                    //验证码设为无效
                    if($code!='99999'){
                        $map=array();
                        $map['id'] = $code_id;
                        $datas['status'] = 1;
                        $re = D('Verification')->edit($map,$datas);
                    }else{
                        $re = true;
                    }
                    if($re){
                        session('user',array(
                            'id'            => $res,
                            'user_name'     => $postdata['user_name'],
                            'nickname'      => $postdata['nickname'],
                            'url_img'       => $postdata['url_img'],
                            'user_phone'    => $postdata['user_phone'],
                            'user_email'    => $postdata['user_email'],
                            'realname'      => $postdata['realname'],
                            'idcard'        => $postdata['idcard'],
                            'card_status'   => $postdata['card_status'],
                            'u_id'   => $uid['u_id'],
                        ));

                        D('User')->commit();
                        $data = array('errorCode'=>1,'msg'=>'注册成功！',"userid"=>$res);
                        //發送註冊成功信息
                        R('Msg/sendmail',array($typename='regmsg',$userid = $res));
                        //給推手發送通知
                        if($referral){
                              R('Msg/sendmail',array($typename='newreg',$userid = $referral));
                        } 
                    }else{
                        D('User')->rollback();
                        $data = array('errorCode'=>5,'msg'=>'注册失败！');
                    }
                   
                }else{
                    D('User')->rollback();//回滚
                    $data = array('errorCode'=>6,'msg'=>'注册失败！');
                }
            }

            $this->ajaxReturn($data);

        
       
    }


    //登录
    public function login() {
            $phone = I('post.phone');
            $password = I('post.password');
            $map['user_phone'] = $phone;
            $data = D('User')->get_one($map);
            //print_r($data);die;
            if($data) {
                if(md5($password . $data['user_mixs']) == ($data['user_pass'])){
                    //登录成功
                    session('user',array(
                                        'id'            => $data['id'],
                                        'user_name'     => $data['user_name'],
                                        'nickname'      => $data['nickname'],
                                        'url_img'       => $data['url_img'],
                                        'user_phone'    => $data['user_phone'],
                                        'realname'      => $data['realname'],
                                        'idcard'        => $data['idcard'],
                                        'card_status'   => $data['card_status'],
                                        'comment_status'   => $data['comment_status'],
                                        'bank_card'   => $data['bank_card'],
                                        'alipay'   => $data['alpay'],
                                        'u_id'   => $data['u_id'],
                                        'role'   => $data['role'],
                                        'url_img' => $data['url_img'],
                                        'rong_token' => $data['rong_token']
                                    ));
                    $map = array();
                    $map['user_id'] = $data['id'];
                    $user_id = $data['id'];
                    $url_img = $data['url_img'];
                    $nickname = $data['nickname'];
                    $data = array();
                    $data['time_last'] = time();
                    $userinfo = D('UserInfo')->edit($map,$data);
                    $data = array('errorCode'=>1,'msg'=>"登录成功",'userid'=>$user_id,'url_img'=>$url_img,'nickname'=>$nickname);
                }else{
                $data = array('errorCode'=>3,'msg'=>"登录密码有误，请重新输入");
                }
            } else {
                $data = array('errorCode'=>2,'msg'=>"该手机号码尚未注册");
            }
            $this->ajaxReturn($data);


        
    }
    

    
    
    //忘記登錄密碼
    public function forgot_password(){
            $postdata['user_phone'] = I('post.phone');
            $code = I('post.code');
            $postdata['user_pass'] = I('post.password');
            $postdata['user_mixs'] = rand(111111,999999);
            $postdata['user_pass'] = md5($postdata['user_pass'].$postdata['user_mixs']);
         //查询验证码是否合法
            $map['phone'] = $postdata['user_phone'];
            $map['status'] = 0;
            $map['role'] = 3;
            $codeinfo = D('Verification')->get_one($map);
            if($codeinfo){
                if($codeinfo['code']==$code && $codeinfo['status']==0){
                    if($codeinfo['time_failure']<=time()){
                        $data = array('errorCode'=>6,'msg'=>'验证码已过期！');
                        $this->ajaxReturn($data);
                    }else{
                        D('User')->startTrans();
                        //验证码有效
                        $map = array();
                        $map['user_phone'] = $postdata['user_phone'];
                        $data['user_mixs'] = $postdata['user_mixs'];
                        $data['user_pass'] = $postdata['user_pass'];
                        $res = D('User')->edit($map,$data);

                        if($res){

                                //验证码设为无效
                                $map=array();
                                $data = array();
                                $map['id'] = $codeinfo['id'];

                                $data['status'] = 1;
                                $re = D('Verification')->edit($map,$data); 
                                if($re){
                                     D('User')->commit();
                                    $data = array('errorCode'=>1,'msg'=>'修改成功！');
                                    $this->ajaxReturn($data);
                                }else{
                                    D('User')->rollback();
                                    $data = array('errorCode'=>5,'msg'=>'修改失败！');
                                    $this->ajaxReturn($data);
                                }
                        }else{
                            D('User')->rollback();
                            $data = array('errorCode'=>4,'msg'=>'修改失败！');
                            $this->ajaxReturn($data);
                        }

                    }
            }else{
                $data = array('errorCode'=>2,'msg'=>'验证码错误！');
                $this->ajaxReturn($data);
            }
        }else{
            $data = array('errorCode'=>3,'msg'=>'验证码无效！');
            $this->ajaxReturn($data);
        }

        
    }
    //实名
    public function realname($realname,$idcard,$val=0){
        if(!$realname && !$idcard){
            $realname = I('post.realname');
            $idcard = I('post.idcard');
            $userid = I('post.userid');
        }
        
        $map['id'] = $userid;
        $user = D('User')->get_one($map);
        if($user['idcards']) {
            $data = array(
                    'err' => 8,
                    'msg' => "您已实名认证"
                );
                if($val){
                 return $data;
                }else{
                 $this->ajaxReturn($data);
                }
        }
        $map = array();
        $map['idcard'] = $idcard;
        $idcards = D('User')->get_one($map);
        if($idcards) {
            $data = array(
                    'err' => 8,
                    'msg' => "身份证已被绑定"
                );
                if($val){
                 return $data;
                }else{
                 $this->ajaxReturn($data);
                }
        }


         if(empty($realname)) {
            $data = array(
                'err' => 7,
                'msg' => "名字不能为空"
            );
            if($val){
                 return $data;
            }else{
                 $this->ajaxReturn($data);
            }
        }
        if(empty($idcard)) {
            $data = array(
                'err' => 8,
                'msg' => "身份证号码不能为空"
            );
            if($val){
                 return $data;
            }else{
                 $this->ajaxReturn($data);
            }
        }
        $map['user_id'] = $userid;
        $re = M('Realname')->where($map)->find();
        if($re){
                $add_day = date('ymd',$re['add_time']);
                $num = $re['num'];
                $today = date('ymd',time());
                    if($num>=5){
                        if($today==$add_day){
                            $data = array(
                                'err' => 4,
                                'msg' => "今天验证次数已经超过5次！明天再来！"
                            );
                        }else{
                            //验证
                            $data =$this->get_real($idcard,$realname,$userid);
                            if($data['err']!=3){
                                $arr_data = array('num'=>1,'add_time'=>time());
                                $map['id'] = $re['id'];
                                $r = M('Realname')->where($re['id'])->save($arr_data);
                            }
                            
                        }
                    }else{
                            $num = $num+1;
                            $number = 5-$num;
                            $data =$this->get_real($idcard,$realname,$number,$userid);
                            if($data['err']!=3){
                                $arr_data = array('num'=>$num,'add_time'=>time());
                                $map['id'] = $re['id'];
                                $r = M('Realname')->where($re['id'])->save($arr_data);
                            }
                            
                    }

        }else{
                        $data = $this->get_real($idcard,$realname,$userid);
                        if($data['err']!=3){
                            $arr_data = array('num'=>1,'add_time'=>time(),'user_id'=>$userid);
                            $r = M('Realname')->data($arr_data)->add();
                        }
        }
        if($val){
            return $data;
        }else{
            $this->ajaxReturn($data);
        }

    }



    public function get_real($idcard,$realname,$userid,$number='4'){
     $real =R('Real/v_real',array($idcard,$realname));
   // $real =Array ( 'reason' => '成功', 'result' => Array ( 'realname' => '王华斌', 'idcard'=>'362427199205230819', 'res'=> 1 ), 'error_code'=> 0 );
    //    $real = '{"reason":"\u6210\u529f","result":{"realname":"\u738b\u534e\u658c","idcard":"362427199205230819","res":1},"error_code":0}';
        $real = json_decode($real,true);
        // print_r($real);
        if($real){
            if($real['error_code']=='0') {

               if($real['result']['res']==1){
                $data = array(
                    'errorCode' => 1,
                    'msg' => "验证成功！"
                );
                //写入用户数据
                $id = $userid;
                $map['id'] = $id;
                $arr_data = array(
                    'realname' => $realname,
                    'idcard'   => $idcard,
                    'card_status' => 1
                );
                $user =D('User')->edit($map,$arr_data);
                //實名成功發送消息
                R('Msg/sendmail',array($typename='realname',$userid = $id));
                // $_SESSION['user']['realname'] = $realname;
                // $_SESSION['user']['idcard'] = $idcard;
                // $_SESSION['user']['card_status'] = 1;
               }else{
                     $data = array(
                        'errorCode' => 2,
                        'msg' => "验证失败，还剩".$number."次机会"
                    );
               }
            } else {
                $data = array(
                    'errorCode' => 3,
                    'msg' =>$real['reason']
                );
            }
        }else{
                    $data = array(
                        'errorCode' => 3,
                        'msg' => "验证请求失败！"
                    );
        }
    return($data);


    }
    private function juhecurl($params = '') {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_URL, $params);
            $json =  curl_exec($ch);
            curl_close($ch);
            $arr=json_decode($json,1);
            return $arr;
    
    }



    //选择圈子
    public function circle(){
        //echo 1;die;
        //平台列表
        $map['status']=1;
        $list = D('Circle')->get_all($map,$field='*');
        $map = array();
        foreach ($list as $k => $v) {
            //加入圈子人数
            $map['platform_id'] = $v['platform_id'];
            $group = M('ImGroup')->where($map)->find();
            $map = array();
            $map['group_id'] = $group['groupid'];
            $map['status'] = 0;
            $group_count = M('ImGroupUser')->where($map)->count();
            $list[$k]['group_count'] = $group_count;
             //深度评测
            $map = array();
            $map['platform_id'] = $v['platform_id'];
            $depth_count = M('OtthAppraisal')->where($map)->count();  //深度评测条数
            $list[$k]['depth_count'] = $depth_count;
            //热门点评
            $commen_count = M('PlatformCommentary')->where($map)->count();//短评条数
            $annou_count = M('CircleAnnounce')->where($map)->count();//信批评论条数
            $opin_count = M('CircleOpinion')->where($map)->count();//舆情条数
            $total_count = $depth_count+$commen_count+$annou_count+$opin_count;//总的热评条数
            $list[$k]['total_count'] = $total_count;
            //区分热门
             $list[$k]['cricel_leve']=$this->get_cricel_leve($v['platform_id']);

             //查询投顾
             $maps = array();
             $maps['push_platform_id'] = $v['platform_id'];
             $push_user= D('Recommend')->get_one($maps);
             //echo D('Recommend')->_sql();
             $maps = array();
             $maps['id'] = $push_user['user_id'];
             $push_user['user'] = D('User')->get_one($maps);
             $list[$k]['push_user'] =$push_user;
         }

        if($list) {
            $data = array('errorCode'=>1,'msg'=>"获取成功！",'data'=>$list);
        } else {
            $data = array('errorCode'=>0,'msg'=>"暂无数据！");
        }
        $this->ajaxReturn($data);
    }


    /**
     * [get_cricel_leve 获取平台评级数据]
     * @param  [type] $platform_id [平台ID]
     * @return [type]              [array]
     */
    public function get_cricel_leve($platform_id){
        $map['platform_id'] = $platform_id;
        $list = M('PlatformGrade')->where($map)->field('count(*) as count,user_role,colligate')->group('user_role,colligate')->order('count(*) desc,colligate asc')->select();
        $list_all = M('PlatformGrade')->where($map)->field('count(*) as count,user_role,colligate')->group('colligate')->order('count(*) desc,colligate asc')->select();
        $count_user = 0;
        $count = 0;
        $count_push = 0;
       // return $list_all;
        foreach ($list_all as $k => $v) {
            $count = $count+$v['count'];
            $all_grade['all_count']=$count;
            $all_grade[]=$v;

        }
        foreach($list as $k=>$v){
            $role = $v['user_role'];

            if($role==1){
                $count_user = $count_user+$v['count'];
                $usre_grade['all_count']=$count_user;
                $usre_grade[]=$v;
            }else{
                $count_push = $count_push+$v['count'];
                $usre_push['all_count']=$count_push;
                $usre_push[]=$v;
            }
        }
        
        foreach ($usre_grade as $k => $v) {
           $count_percent = sprintf("%.0f",$v['count']/$usre_grade['all_count']*100);
           $usre_grade[$k]['count_percent']=$count_percent;
           $usre_grade[$k]['usre_grade']=$usre_grade['all_count'];
        }
        //unset($usre_grade['all_count']);
        
        foreach ($usre_push as $k => $v) {
           $count_percent = sprintf("%.0f",$v['count']/$usre_push['all_count']*100);
           $usre_push[$k]['count_percent']=$count_percent;
           $usre_push[$k]['usre_grade']=$usre_push['all_count'];
        }
        //unset($usre_push['all_count']);
        foreach ($all_grade as $k => $v) {
           $count_percent = sprintf("%.0f",$v['count']/$all_grade['all_count']*100);
           $all_grade[$k]['count_percent']=$count_percent;
           $all_grade[$k]['usre_grade']=$all_grade['all_count'];
        }
       // unset($usre_push['all_count']);
        $data = array('usre_grade'=>$usre_grade[0],'usre_push'=>$usre_push[0],'all_grade'=>$all_grade[0]);
        return ($data);
    }


    //注册后师傅列表
    public function master() {
        if(IS_POST){
             $plat_id = I('post.plat_id');
             $p = I('post.currentPage');
             $p = $p*5;
        }else{
            $plat_id = I('get.plat_id');
            $p=0;
        }
        $pagenum = 5;
        
        if($plat_id) {
            $map['jg_recommend_platform.platform_id'] = $plat_id;
            $map['jg_recommend_platform.status'] = 1;
        } else {
            $map['jg_recommend_platform.status'] = 1;
            $group = 'jg_recommend_platform.recommend_id';
        }
        // $recom = D('RecommendPlatform')->get_all($map);
        $field = "jg_recommend_platform.*,jg_recommend.user_id,jg_recommend.fans,jg_recommend.year,jg_recommend.platform_num,jg_recommend.pit_num";
        $recom = M('RecommendPlatform')->join('RIGHT JOIN jg_recommend ON jg_recommend_platform.recommend_id = jg_recommend.id')->field($field)->order('jg_recommend.fans desc')->where($map)->group($group)->limit($p,$pagenum)->select();
        //echo M('RecommendPlatform')->_sql();die;
        $map = array();
        $recommend_id=0;
        foreach($recom as $k => $v) {
            if($recommend_id == $v['recommend_id']){
                unset($recom[$k]);
            }
            $recommend_id = $v['recommend_id'];
            $map = array();
            $map['id'] = $v['user_id'];
            $user = D('User')->get_one($map);
            $recom[$k]['user'] = $user;
             //派系
                $map = array();
                $map['user_id'] = $v['user_id'];
                $factions = M('Factions')->where($map)->find();
                $recom[$k]['factions'] = $factions;
            //技能
                $skill = M('Skill')->where($map)->find();
                $skill = explode(',',$skill['skill']);
                $recom[$k]['skill'] = $skill;
            //师傅圈子
                $map = array();
                $map['recommend_id'] = $v['id'];
                $platform = D('RecommendPlatform')->get_all($map,'*',0,2);
                $map = array();
                foreach($platform as $ke => $va) {
                    $map['id'] = $va['platform_id'];
                    $plat = D('Platform')->get_one($map,'name');
                    $plat_list[] = $plat['name'];
                    $recom[$k]['plat'] = $plat_list;
                }

         }

        if($recom) {
            $data = array('errorCode'=>1,'msg'=>"获取成功！",'data'=>$recom);
        } else {
            $data = array('errorCode'=>0,'msg'=>"暂无数据！");
        }
        $this->ajaxReturn($data);

    }




}